import {
	HEADER,
	TOKENNAME,
	HTTP_REQUEST_URL
} from "../config";
/**
 * 发送请求
 */

export default function request(api, method, data, type) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	let token = uni.getStorageSync('token')
	header['X-Access-Token'] = token
	if (type) {
		header = JSON.parse(JSON.stringify(header))
		header['content-type'] = 'application/x-www-form-urlencoded'
	}
	// header['Content-Type'] = 'application/x-www-form-urlencoded'
	return new Promise((reslove, reject) => {
		uni.showLoading();
		wx.request({
			url: Url + api,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: res => {
				if (res.data.code == '401') {
					setTimeout(() => {
						// uni.clearStorageSync();
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');
						uni.showModal({
							title: '提示',
							content: '点击确认跳转登录',
							success: function(res) {
								if (res.confirm) {
									uni.switchTab({
										url: '/pages/info/info'
									})
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}, 1000)

				} else if (res.data.code == 200) reslove(res.data, res);
				else if (res.data.code == 500) reslove(res.data, res);
				else if (res.data.code == 0) reslove(res.data, res);
				else if (res.data.code == 400) reslove(res.data, res);
				else if (res.data.code == 402) reslove(res.data, res);
				else if (res.data.code == 40009) reslove(res.data, res);
				else {
					uni.showToast({
						icon: "none",
						title: res.data.msg
					})
					reject(res.data.msg || '系统错误');
				}
				uni.hideLoading();
			},
			fail: msg => {
				reject('请求失败');
				uni.hideLoading();
			}
		});
	})
}
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach(method => {
	request[method] = (api, data, opt, type) => request(api, method, data, opt || {}, type);
});